import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn'
import relativeTime from 'dayjs/plugin/relativeTime'

// 配置dayjs
dayjs.locale('zh-cn')
dayjs.extend(relativeTime)

/**
 * 格式化日期时间
 * @param {string|Date} date 日期
 * @param {string} format 格式
 * @returns {string} 格式化后的日期字符串
 */
export const formatDate = (date, format = 'YYYY-MM-DD HH:mm:ss') => {
  if (!date) return ''
  return dayjs(date).format(format)
}

/**
 * 格式化相对时间
 * @param {string|Date} date 日期
 * @returns {string} 相对时间字符串
 */
export const formatRelativeTime = (date) => {
  if (!date) return ''
  return dayjs(date).fromNow()
}

/**
 * 检查日期是否已过期
 * @param {string|Date} date 日期
 * @returns {boolean} 是否已过期
 */
export const isExpired = (date) => {
  if (!date) return false
  return dayjs(date).isBefore(dayjs())
}

/**
 * 检查日期是否即将到期（24小时内）
 * @param {string|Date} date 日期
 * @returns {boolean} 是否即将到期
 */
export const isExpiringSoon = (date) => {
  if (!date) return false
  const now = dayjs()
  const target = dayjs(date)
  return target.isAfter(now) && target.diff(now, 'hour') <= 24
}

/**
 * 获取活动状态
 * @param {Object} activity 活动对象
 * @returns {Object} 状态信息
 */
export const getActivityStatus = (activity) => {
  const now = dayjs()
  const startTime = dayjs(activity.startTime)
  const endTime = dayjs(activity.endTime)
  const registrationDeadline = dayjs(activity.registrationDeadline)
  
  if (now.isBefore(registrationDeadline)) {
    return {
      status: 'registration',
      text: '报名中',
      type: 'success'
    }
  } else if (now.isBefore(startTime)) {
    return {
      status: 'waiting',
      text: '等待开始',
      type: 'warning'
    }
  } else if (now.isBefore(endTime)) {
    return {
      status: 'ongoing',
      text: '进行中',
      type: 'primary'
    }
  } else {
    return {
      status: 'ended',
      text: '已结束',
      type: 'info'
    }
  }
}

/**
 * 获取报名状态文本和类型
 * @param {string} status 报名状态
 * @returns {Object} 状态信息
 */
export const getRegistrationStatus = (status) => {
  const statusMap = {
    PENDING: { text: '待审核', type: 'warning' },
    APPROVED: { text: '已通过', type: 'success' },
    REJECTED: { text: '已拒绝', type: 'danger' }
  }
  return statusMap[status] || { text: '未知', type: 'info' }
}

/**
 * 防抖函数
 * @param {Function} func 要防抖的函数
 * @param {number} wait 等待时间
 * @returns {Function} 防抖后的函数
 */
export const debounce = (func, wait) => {
  let timeout
  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeout)
      func(...args)
    }
    clearTimeout(timeout)
    timeout = setTimeout(later, wait)
  }
}

/**
 * 节流函数
 * @param {Function} func 要节流的函数
 * @param {number} limit 时间限制
 * @returns {Function} 节流后的函数
 */
export const throttle = (func, limit) => {
  let inThrottle
  return function executedFunction(...args) {
    if (!inThrottle) {
      func.apply(this, args)
      inThrottle = true
      setTimeout(() => inThrottle = false, limit)
    }
  }
}

/**
 * 深拷贝
 * @param {any} obj 要拷贝的对象
 * @returns {any} 拷贝后的对象
 */
export const deepClone = (obj) => {
  if (obj === null || typeof obj !== 'object') return obj
  if (obj instanceof Date) return new Date(obj.getTime())
  if (obj instanceof Array) return obj.map(item => deepClone(item))
  if (typeof obj === 'object') {
    const clonedObj = {}
    for (const key in obj) {
      if (obj.hasOwnProperty(key)) {
        clonedObj[key] = deepClone(obj[key])
      }
    }
    return clonedObj
  }
}

/**
 * 生成随机ID
 * @param {number} length ID长度
 * @returns {string} 随机ID
 */
export const generateId = (length = 8) => {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  let result = ''
  for (let i = 0; i < length; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length))
  }
  return result
}

/**
 * 验证邮箱格式
 * @param {string} email 邮箱地址
 * @returns {boolean} 是否有效
 */
export const validateEmail = (email) => {
  const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  return re.test(email)
}

/**
 * 验证手机号格式
 * @param {string} phone 手机号
 * @returns {boolean} 是否有效
 */
export const validatePhone = (phone) => {
  const re = /^1[3-9]\d{9}$/
  return re.test(phone)
}

/**
 * 文件大小格式化
 * @param {number} bytes 字节数
 * @returns {string} 格式化后的大小
 */
export const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}